<?php
namespace Home\Controller;
use Lib\Api\AgentApi;
use Lib\Api\AgentSettlementApi;
use Lib\Api\OrderApi;
use Lib\Api\OrderCommissionApi;
use Lib\Api\OrganizationApi;
use Lib\Api\OrganizationSettlementApi;
use Lib\Api\OrganizationStatisticsApi;
use Lib\Api\TradeDetailApi;
use Lib\Api\UserApi;
use Lib\Api\UserBelongApi;
use Think\Controller;
class OrderController extends Controller {

    public function index(){
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        if (empty(session('user_id'))) {
            // session('user_id', 1);
            $this->display('User/login');
        } else {
            $week = getWeek();

            $modelName = 'User';
            $modelObj = M($modelName);
            $data = $modelObj->where(array('id' => session('user_id')))->find();
            $this->assign('user', $data);

            $modelName = 'Game_type';
            $modelObj = M($modelName);
            $list = $modelObj->where(array('state'=>1))->order('sort asc')->select();

            for ($i=0; $i<count($list); $i++) {
                if ($list[$i][$week] == 1) {
                    $list[$i]["isRest"] = 1;
                } else {
                    $list[$i]["isRest"] = 2;
                }
            }
            $this->assign('games', $list);

            $this->display();
        }
    }

    // 开奖接口
    public function open_lottery() {
        $order_no = $_GET['order_no'];
        $close_price = $_GET['close_price'];
        $state = $_GET['state'];
        $end_time = $_GET['end_time'];

        $path = "C:/HwsApacheMaster/wwwroot/maijiyi_N1VnIM/log/order/";
        if (!is_dir($path)){
            mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $file = $path.'open_lottery_'.date('Y-m-d').'.txt';    // 写入的文件
        $log = "订单开奖 -- 订单号：".$order_no."，价格：".$close_price."，盈亏：".$state."，开奖时间：".$end_time;
        file_put_contents($file,$log,FILE_APPEND);
        $order = OrderApi::getInfo(array("order_no"=>$order_no, 'state'=>0));
        if (!empty($order)) {
            $log = "\r\n获取到订单准备开奖";
            file_put_contents($file,$log,FILE_APPEND);

            // 计算头寸，手续费
            $fee = ($order['order_price'] - $order['voucher_price']) * ($order['order_fee'] / 100);
            $head = $order['order_price'] - $order['voucher_price'] - $fee;
            if ($state == 1) {
                $gain_price = ($head - $order['voucher_price']) * ($order['profit_rate'] / 100);
            } else {
                $gain_price = -($head - $order['voucher_price']);
            }
            $order['gain_price'] = $gain_price;
            $order['state'] = $state;
            $order['close_price'] = $close_price;
            $order['end_time'] = $end_time;

            $log = "\r\n计算得出订单头寸为：".$head."元，手续费为：".$fee."元，盈亏金额为：".$gain_price."元；准备更新订单信息";
            file_put_contents($file,$log,FILE_APPEND);
            $rel = OrderApi::save($order);
            $log = "\r\n订单信息已更新，结果：".$rel;
            file_put_contents($file,$log,FILE_APPEND);
            if ($rel > 0) {
                // 更新用户余额
                $log = "\r\n准备更新用户余额";
                file_put_contents($file,$log,FILE_APPEND);
                $balance = $head + $gain_price;
                $type = 3;
                if ($state == 1) {
                    $user['balance'] = array('exp','balance+'.$balance);
                    $type = 2;
                }
                $user['id'] = $order['user_id'];
                $user['freeze_balance'] = array('exp','freeze_balance-'.($order['real_price']*$order['mun']-$order['voucher_price']));
                $userModel = M("User");
                $userObj = $userModel->create($user);
                UserApi::save($userObj);
                $user = UserApi::getInfo(array('id'=>$order['user_id']), 'balance');
                $log = "\r\n用户余额已更新，更新后余额：".$user['balance']."元";
                file_put_contents($file,$log,FILE_APPEND);

                $log = "\r\n准备用户交易明细数据";
                file_put_contents($file,$log,FILE_APPEND);
                // 保存交易明细
                $tradeDetail = array("user_id"=>$order['user_id'], "deal_user_id"=>0, "out_trade_no"=>"$order_no", "type"=>$type,
                    "money"=>$gain_price, "fee_money"=>$fee, "other_money"=>$head,"balance"=>$user['balance'],
                    "source"=>1,"state"=>1, "datetime"=>$end_time);
                TradeDetailApi::add($tradeDetail);
                $log = "\r\n保存用户交易明细数据";
                file_put_contents($file,$log,FILE_APPEND);

                // 更新代理保证金
                $log = "\r\n获取代理机构，用于更新保证金";
                file_put_contents($file,$log,FILE_APPEND);
                $AGENTCONFIG = C('AGENTCONFIG');
                $level = 0;
                for ($i=0; $i<count($AGENTCONFIG); $i++) {
                    if ($AGENTCONFIG[$i]['type'] == 'dl') {
                        $level = $AGENTCONFIG[$i]['level'];
                        break;
                    }
                }
                // 获取代理机构
                $map['a.user_id'] = $order['user_id'];
                $map['a.organization_level'] = $level;
                $map['DATE_FORMAT(a.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.$order['begin_time'].'", "%Y-%m-%d %H:%i:%s")');
                $left = "left join fs_organization b on b.id = a.organization_id";
                $belongOrg = UserBelongApi::getUserBelongOrgByCondition($map, $left, "b.*");
                $log = "\r\n获取到代理机构“".$belongOrg['name']."”，ID：".$belongOrg['id']."，准备为其更新保证金";
                file_put_contents($file,$log,FILE_APPEND);
                // $dl_gain_price = 0;
                if ($state == 1) {
                    // $gain_price
                    $dl_gain_price = -$head;
                    $belongOrg['balance'] = array('exp','balance-'.$head);
                } else {
                    $dl_gain_price = $head;
                    $belongOrg['balance'] = array('exp','balance+'.$head);
                }
                // $belongOrg['deposit'] = array('exp','deposit+'.$gain_price);
                OrganizationApi::save($belongOrg);
                $log = "\r\n完成更新代理机构保证金";
                file_put_contents($file,$log,FILE_APPEND);

                // 获取经纪人信息
                $log = "\r\n获取推荐经纪人返佣信息";
                file_put_contents($file,$log,FILE_APPEND);
                $orderCommission_list = OrderCommissionApi::getListByCondition(array("a.order_id"=>$order["id"]), "", 1, 9999, "*", "","a.commission_level asc");
                if (empty($orderCommission_list)) {
                    $log = "\r\n未获取到推荐经纪人返佣信息";
                    file_put_contents($file,$log,FILE_APPEND);
                }

                /*$agent_map['c.id'] = $order['user_id'];
                $agent_map['a.game_type'] = $order['play_type'];
                $agent_map['b.state'] = 1;
                $agent_map['DATE_FORMAT(take_effect_time, "%Y-%m-%d %H:%i:%s")'] = array("elt", "DATE_FORMAT('".$order['begin_time']."', '%Y-%m-%d %H:%i:%s')");
                $left = "left join fs_agent b on b.id = a.agent_id";
                $left .= " left join fs_user c on c.recommend_id = b.id";
                $field = 'a.commission_ratio, b.id as agent_id';
                $agentCommissionSetList = AgentCommissionSetApi::getListByCondition($agent_map, $left, $field, 'a.take_effect_time desc', 1, 1);
                $agent_id = 0;
                $agent_fee = 0;
                if (!empty($agentCommissionSetList)) {
                    $agent_id = $agentCommissionSetList[0]['agent_id'];
                    $log = "\r\n获取到推荐经纪人返佣信息";
                    file_put_contents($file,$log,FILE_APPEND);
                } else {
                    $log = "\r\n未获取到推荐经纪人返佣信息，或经纪人已被禁用";
                    file_put_contents($file,$log,FILE_APPEND);
                }*/

                $log = "\r\n准备机构每日结算数据";
                file_put_contents($file,$log,FILE_APPEND);
                $organization_map['a.user_id'] = $order['user_id'];
                $organization_map['DATE_FORMAT(a.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.$order['begin_time'].'", "%Y-%m-%d %H:%i:%s")');
                $organization_map['a.state'] = 1;
                $field = "c.id, d.id as statistics_id, b.id as organization_id, b.level, b.name as organization_name, (select commission_ratio from fs_organization_commission_set where organization_id = b.id and game_type = ".$order['play_type']." and  DATE_FORMAT(take_effect_time, '%Y-%m-%d %H:%i:%s') <= DATE_FORMAT('".$order['begin_time']."', '%Y-%m-%d %H:%i:%s') order by take_effect_time desc limit 1) as commission_ratio";
                $left = " left join fs_organization b on b.id = a.organization_id";
                $left .= " left join fs_organization_settlement c on c.organization_id = b.id and c.state = 2";
                $left .= " left join fs_organization_statistics d on d.organization_id = b.id and d.state = 2";
                // $left .= "left join fs_customer c on c.organization_id = b.id";
                $organizations = UserBelongApi::getAllUserBelongList($organization_map, $left, $field, "a.organization_level asc");

                if (count($organizations) > 0) {
                    $agent_fee = 0;

                    $sys_total_fee = $fee;
                    $total_fee = $fee;
                    $sql = "insert into fs_organization_settlement (id, sys_total_fee, total_fee, settlement_money, cash_profit_loss, cash_income)";
                    $sql .= " values ";
                    $sqlValues = array();

                    $sql_statistics = "insert into fs_organization_statistics (id, fee, cash_profit_loss, count_profit, relation_fee, original_fee, turnover)";
                    $sql_statistics .= " values ";
                    $sqlStatisticsValues = array();

                    for ($i=0;$i<count($organizations);$i++) {
                        $isAnget = false;
                        $commission_ratio = $organizations[$i]['commission_ratio'];
                        if (empty($commission_ratio)) {
                            $commission_ratio = 0;
                        }
                        $junior_commission_ratio = 0;
                        if ($i+1 < count($organizations)) {
                            $junior_commission_ratio = $organizations[$i+1]['commission_ratio'];
                        } else if ($i+1 == count($organizations)) {
                            if (!empty($orderCommission_list)) {
                                for ($j=0; $j<count($orderCommission_list); $j++) {
                                    if ($orderCommission_list[$j]['commission_level'] == 0) {
                                        $junior_commission_ratio = $orderCommission_list[$j]['commission_ratio'];
                                        // $agent_fee = round($total_fee*($commission_ratio/100)*($junior_commission_ratio/100));
                                        // $orderCommission_list[$j]['commission_ratio'] = 100;
										
										$agent_fee = $total_fee*($commission_ratio/100)*($junior_commission_ratio/100);
										
                                        $isAnget = true;
                                    }
                                }
                            }

                            /*if (!empty($agentCommissionSetList)) {
                                $junior_commission_ratio = $agentCommissionSetList[0]['commission_ratio'];
                                $agent_fee = $total_fee*($commission_ratio/100) - $total_fee*($commission_ratio/100)*($junior_commission_ratio/100);
                            }*/
                        }

                        $total_fee = $total_fee*($commission_ratio/100);
                        $junior_fee = $total_fee*($junior_commission_ratio/100);
                        /*if ($isAnget == true) {
                            $junior_fee = round($total_fee*($junior_commission_ratio/100));
                        } else {
                            $junior_fee = $total_fee*($junior_commission_ratio/100);
                        }*/
                        $settlement_money = $total_fee-$junior_fee;
                        $cash_profit_loss = 0;
                        $turnover = 0;
                        $AGENTCONFIG = C('AGENTCONFIG');
                        if ($AGENTCONFIG[$organizations[$i]['level']]['setting'][0] == 1) {
                            $cash_profit_loss = $dl_gain_price;
                            $turnover = $order['real_price']*$order['mun'];
                        }
                        $cash_income = $settlement_money + $cash_profit_loss;

                        $log = "\r\n机构：".$organizations[$i]['organization_name']."，总手续费：".$sys_total_fee."，应得返佣：".$total_fee."，扣除下级返佣：".$junior_fee . "，实际返佣：".$settlement_money . "，现金盈亏：".$cash_profit_loss."，账户实际收入为：".$cash_income;
                        file_put_contents($file,$log,FILE_APPEND);

                        $sqlValue = "(".$organizations[$i]['id'].", ".$sys_total_fee.", ".$total_fee.", ".$settlement_money.", ".$cash_profit_loss.", ".$cash_income.")";
                        array_push($sqlValues, $sqlValue);

                        $sqlStatisticsValue = "(".$organizations[$i]['statistics_id'].", ".$settlement_money.", ".$cash_profit_loss.", ".$cash_income.", ".$total_fee.", ".$sys_total_fee.", ".$turnover.")";
                        array_push($sqlStatisticsValues, $sqlStatisticsValue);
                    }
                    $sql .= implode(",", $sqlValues);
                    $sql .= " on duplicate key update";
                    $sql .=" sys_total_fee=sys_total_fee+values(sys_total_fee),";
                    $sql .="total_fee=total_fee+values(total_fee),";
                    $sql .="settlement_money=settlement_money+values(settlement_money),";
                    $sql .="cash_profit_loss=cash_profit_loss+values(cash_profit_loss),";
                    $sql .="cash_income=cash_income+values(cash_income)";

                    $sql_statistics .= implode(",", $sqlStatisticsValues);
                    $sql_statistics .= " on duplicate key update";
                    $sql_statistics .=" fee=fee+values(fee),";
                    $sql_statistics .="cash_profit_loss=cash_profit_loss+values(cash_profit_loss),";
                    $sql_statistics .="count_profit=count_profit+values(count_profit),";
                    $sql_statistics .="relation_fee=relation_fee+values(relation_fee),";
                    $sql_statistics .="original_fee=original_fee+values(original_fee),";
                    $sql_statistics .="turnover=turnover+values(turnover)";

                    $log = "\r\n机构每日结算数据准备完毕，进行更新操作";
                    file_put_contents($file,$log,FILE_APPEND);
                    $model = M();
                    $model->execute($sql);

                    $model = M();
                    $model->execute($sql_statistics);

                    $log = "\r\n机构每日结算数据更析完毕";
                    file_put_contents($file,$log,FILE_APPEND);

                    if ($agent_fee > 0) {
                        $total_fee = $agent_fee;
                        if (!empty($orderCommission_list)) {
                            $log = "\r\n更新经纪人每日结算数据";
                            file_put_contents($file,$log,FILE_APPEND);

                            for ($i=0; $i<count($orderCommission_list); $i++) {
                                if ($i == 0) {
                                    $commission_ratio = 100;
                                } else {
                                    $commission_ratio = $orderCommission_list[$i]['commission_ratio'];
                                }

                                if (empty($commission_ratio)) {
                                    $commission_ratio = 0;
                                }
                                $junior_commission_ratio = 0;
                                if ($i+1 < count($orderCommission_list)) {
                                    $junior_commission_ratio = $orderCommission_list[$i+1]['commission_ratio'];
                                }

                                $total_fee = $total_fee*($commission_ratio/100);
                                $junior_fee = $total_fee*($junior_commission_ratio/100);
                                $settlement_money = $total_fee-$junior_fee;

                                $agentSettlement = AgentSettlementApi::getInfo(array("agent_id"=>$orderCommission_list[$i]["agent_id"], "state"=>2));
                                $agentSettlement['sys_total_fee'] = array('exp','sys_total_fee+'.$fee); // $fee;
                                $agentSettlement['total_fee'] = array('exp','total_fee+'.$total_fee); // $total_fee;
                                $agentSettlement['settlement_money'] = array('exp','settlement_money+'.$settlement_money); // $settlement_money;
                                AgentSettlementApi::save($agentSettlement);

                                $orderCommission_list[$i]["commission_money"] = $settlement_money;

                                OrderCommissionApi::save($orderCommission_list[$i]);

                                $log = "\r\n经纪人ID：".$orderCommission_list[$i]['agent_id']."，总手续费：".$sys_total_fee."，应得返佣：".$total_fee."，扣除下级返佣：".$junior_fee . "，实际返佣：".$settlement_money;
                                file_put_contents($file,$log,FILE_APPEND);
                            }

                            $log = "\r\n经纪人每日结算数据更析完毕";
                            file_put_contents($file,$log,FILE_APPEND);
                        }

                        /*$rebateRatio = RebateRatioApi::getRebateRatioByCondition(array("game_type"=>$order['play_type']), "rebate_ratio");
                        $REBATELAYER = C('TMPL_PARSE_STRING.__REBATELAYER__');
                        if ($REBATELAYER > 0) {
                            $p_agent_id = $agent_id;
                            $p_agent_fee = $total_fee;
                            for ($i=0; $i<$REBATELAYER; $i++) {
                                $left = "left join fs_user b on b.agent_id = a.id";
                                $left .= " left join fs_agent c on c.id = b.recommend_id";
                                $left .= " left join fs_user d on d.agent_id = c.id";
                                $agent = AgentApi::getInfo(array("a.id"=>$p_agent_id), $left, "c.id, d.recommend_id ");
                                if (!empty($agent)) {
                                    if ($i == 0) {
                                        $junior_agent_fee = $p_agent_fee*($rebateRatio['rebate_ratio']/100);
                                    }
                                    $p_agent_fee = $p_agent_fee*($rebateRatio['rebate_ratio']/100);

                                    $junior_p_agent_fee = 0;
                                    if ($agent['recommend_id'] > 0 && ($i+1) < $REBATELAYER) {
                                        $junior_p_agent_fee = $p_agent_fee*($rebateRatio['rebate_ratio']/100);
                                    }
                                    $settlement_money = $p_agent_fee-$junior_p_agent_fee;

                                    $agentSettlement = AgentSettlementApi::getInfo(array("agent_id"=>$p_agent_id, "state"=>2));
                                    $agentSettlement['sys_total_fee'] = $fee;
                                    $agentSettlement['total_fee'] = $p_agent_fee;
                                    $agentSettlement['settlement_money'] = $settlement_money;
                                    AgentSettlementApi::save($agentSettlement);

                                    $order_commission["order_id"] = $order['id'];
                                    $order_commission["customer_id"] = $p_agent_id;
                                    $order_commission["customer_level"] = 4;
                                    $order_commission["total_fee"] = $fee;
                                    $order_commission["fee"] = $p_agent_fee;
                                    $order_commission["commission_money"] = $settlement_money;
                                    $order_commission["commission_ratio"] = $rebateRatio['rebate_ratio'];
                                    $order_commission["state"] = 1;
                                    $order_commission["datetime"] = date('Y-m-d H:i:s');
                                    OrderCommissionApi::add($order_commission);

                                    $p_agent_id = $agent['recommend_id'];
                                }
                            }
                        }*/
                    }
                }
            }
        } else {
            $log = "\r\n订单不存在或已开奖";
            file_put_contents($file,$log,FILE_APPEND);
        }

        $log = "\r\n开奖完成";
        file_put_contents($file,$log,FILE_APPEND);
        $log = "\r\n------------------------------------------------------------------------------\r\n";
        file_put_contents($file,$log,FILE_APPEND);
        $r['state'] = 'ok';
        $this->ajaxReturn($r);
    }

    // 订单结算
    public function statements() {
        $order_map['state'] = 0;
        $order_list = OrderApi::getListByCondition($order_map);
        if (!empty($order_list)) {
            // $close_price = $_GET['close_price'];
            // $end_time = $_GET['end_time'];
            $end_time = date('Y-m-d H:i:s');
            // 更新订单表及用户表数据
            $sql = 'update fs_order a inner join fs_user b on a.user_id = b.id inner join fs_temp_data d on d.type = a.play_type set b.freeze_balance=b.freeze_balance-a.order_price,b.balance = b.balance+(a.real_price*a.mun),a.gain_price=0, a.close_price=d.value, a.end_time="'.$end_time.'", a.state=3 where a.state=0';
            $model = M();
            $f = $model->execute($sql);
            // 保存交易明细
            if ($f > 0) {
                $add_trade_detail_arr = array();
                for ($i=0; $i<count($order_list); $i++) {
                    $user = UserApi::getInfo(array('id'=>$order_list[$i]['user_id']), 'balance');
                    $tradeDetail['user_id'] = $order_list[$i]['user_id'];
                    $tradeDetail['deal_user_id'] = 0;
                    $tradeDetail['out_trade_no'] = $order_list[$i]['order_no'];
                    $tradeDetail['type'] = 4;
                    $tradeDetail['money'] = $order_list[$i]['order_price']-$order_list[$i]['voucher_price'];
                    $tradeDetail['fee_money'] = 0;
                    $tradeDetail['other_money'] = 0;
                    $tradeDetail['balance'] = $user['balance'];
                    $tradeDetail['source'] = 1;
                    $tradeDetail['state'] = 1;
                    $tradeDetail['datetime'] = $end_time;
                    array_push($add_trade_detail_arr, $tradeDetail);
                }
                if (count($add_trade_detail_arr) > 0) {
                    TradeDetailApi::addAll($add_trade_detail_arr);
                }
            }
        }

        // 机构结算
        $sql = 'update fs_organization a INNER JOIN fs_organization_settlement b on b.organization_id=a.id set a.balance=a.balance+b.settlement_money, b.state=1, b.settlement_date=now() where b.state=2';
        $model = M();
        $model->execute($sql);

        // 经纪人结算
        $sql = 'update fs_agent a INNER JOIN fs_agent_settlement b on b.agent_id=a.id set a.balance=a.balance+b.settlement_money, b.state=1, b.settlement_date=now() where b.state=2';
        $model = M();
        $model->execute($sql);

        // 更新统计表
        $sql = 'update fs_organization_statistics a INNER JOIN fs_organization b on b.id = a.organization_id set a.end_balance = b.balance, a.state=1, a.settlement_date=now() where a.state=2';
        $model = M();
        $model->execute($sql);

        // 更新订单返佣
        $sql = 'update fs_order_commission set state=1 where state=2';
        $model = M();
        $model->execute($sql);

        $begin_time = date("Y-m-d H:i:s");
        $end_time = date("Y-m-d H:i:s",strtotime($begin_time."+1 day"));

        // 获取所有机构
        $organization_list = OrganizationApi::getListAll(array(), "id,level,balance");
        if (!empty($organization_list)) {
            $add_organizationStatistics_arr = array();
            $add_organizationSettlement_arr = array();
            for ($i=0; $i<count($organization_list); $i++) {

                $organizationStatistics["organization_id"] = $organization_list[$i]["id"];
                $organizationStatistics["begin_balance"] = $organization_list[$i]["balance"];
                $organizationStatistics["recharge"] = 0;
                $organizationStatistics["recharge_fee"] = 0;
                $organizationStatistics["withdrawals"] = 0;
                $organizationStatistics["withdrawals_fee"] = 0;
                $organizationStatistics["retained_money"] = 0;
                $organizationStatistics["fee"] = 0;
                $organizationStatistics["cash_profit_loss"] = 0;
                $organizationStatistics["count_profit"] = 0;
                $organizationStatistics["relation_fee"] = 0;
                $organizationStatistics["original_fee"] = 0;
                $organizationStatistics["turnover"] = 0;
                $organizationStatistics["end_balance"] = 0;
                $organizationStatistics["state"] = 2;
                $organizationStatistics["begin_time"] = $begin_time;
                $organizationStatistics["end_time"] = $end_time;
                array_push($add_organizationStatistics_arr, $organizationStatistics);

                $organizationSettlement["organization_id"] = $organization_list[$i]["id"];
                $organizationSettlement["organization_level"] = $organization_list[$i]["level"];
                $organizationSettlement["sys_total_fee"] = 0;
                $organizationSettlement["total_fee"] = 0;
                $organizationSettlement["settlement_money"] = 0;
                $organizationSettlement["cash_profit_loss"] = 0;
                $organizationSettlement["cash_income"] = 0;
                $organizationSettlement["state"] = 2;
                $organizationSettlement["begin_time"] = $begin_time;
                $organizationSettlement["end_time"] = $end_time;
                array_push($add_organizationSettlement_arr, $organizationSettlement);
            }
            if (count($add_organizationSettlement_arr) > 0) {
                OrganizationSettlementApi::addAll($add_organizationSettlement_arr);
            }
            if (count($add_organizationStatistics_arr) > 0) {
                OrganizationStatisticsApi::addAll($add_organizationStatistics_arr);
            }
        }

        // 获取所有经纪人
        $agent_list = AgentApi::getListAll(array("state"=>1),"" , "id");
        if (!empty($agent_list)) {
            $add_agentSettlement_arr = array();
            for ($i = 0; $i < count($agent_list); $i++) {
                $agentSettlement["agent_id"] = $agent_list[$i]["id"];
                $agentSettlement["sys_total_fee"] = 0;
                $agentSettlement["total_fee"] = 0;
                $agentSettlement["settlement_money"] = 0;
                $agentSettlement["state"] = 2;
                $agentSettlement["begin_time"] = $begin_time;
                $agentSettlement["end_time"] = $end_time;
                array_push($add_agentSettlement_arr, $agentSettlement);
            }
            if (count($add_agentSettlement_arr)>0) {
                AgentSettlementApi::addAll($add_agentSettlement_arr);
            }
        }

        /*$organizationSettlement = OrganizationSettlementApi::getList(array("a.state"=>2));
        if (!empty($organizationSettlement)) {
            for ($i=0; $i<count($organizationSettlement); $i++) {
            }
        }*/


        $r['state'] = 'ok';
        $this->ajaxReturn($r);
    }

    public function orderList() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $pageNo = $_POST['page'];
        $pageSize = $_POST['pageSize'];
        // $pageNo = (intval($pageNo)-1) * intval($pageSize);
        $type = $_POST["type"];
        $state = $_POST["state"];
        $user_id = session('user_id');

        // $orderModel = M('Order');
        $model = M();
        $where['a.user_id'] = $user_id;
        if ($type != 0) {
            $where["a.play_type"] = $type;
        }
        if ($state == 0) {
            $where["a.state"] = "0";
        } else if($state == 1) {
            $where["a.state"] = array('neq',0);
            $where['DATE_FORMAT(a.end_time, "%Y-%m-%d")'] = array('eq',date('Y-m-d'));
        } else if ($state == 2) {
            $where["a.state"] = array('neq',0);
        }
        $field = "a.order_no,a.type,a.play_type,a.order_price,a.real_price,a.voucher_price,a.mun,a.end_time,a.begin_time,a.gain_price,a.state,b.show_name,a.open_price,a.close_price,ifnull(c.fee_money, 0) as fee_money";
        $list = $model->table('fs_order a')
            ->join('left join fs_game_type b on b.id = a.play_type')
            ->join('left join fs_trade_detail c on c.out_trade_no = a.order_no and (c.type = 2 or c.type = 3 or c.type=4)')
            //->field('r.name, sm.name, m.id')
            ->field($field)
            ->where($where)
            ->page($pageNo, $pageSize)
            ->order('a.begin_time desc')
            ->select();

        $totals = $model->table('fs_order a')->where($where)->count("a.id");

        $return_list['totals'] = $totals;
        $return_list["success"] = 1;
        $return_list["data"] = $list;
        $return_list["CurrDateTime"] = date('Y-m-d H:i:s');

        $this->ajaxReturn($return_list);
    }

    public function newOrderList() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $pageNo = $_POST['page'];
        $pageSize = $_POST['pageSize'];
        $model = M();
        $field = "b.game_name as symbol,a.type as direction,a.order_price as buycount,DATE_FORMAT(a.create_date, '%H:%i:%s') as subtime";
        $list = $model->table('fs_order_virtual a')
            //->field('r.name, sm.name, m.id')
            ->join('left join fs_game_type b on b.id = a.play_type')
            ->field($field)
            ->page($pageNo, $pageSize)
            ->order('a.create_date desc')
            ->select();

        $return_list["success"] = 1;
        $return_list["data"] = $list;

        $this->ajaxReturn($return_list);
    }

}